package cn.xy.org.controller;

import cn.xy.basic.anno.PreAuthorize;
import cn.xy.basic.util.AjaxResult;
import cn.xy.basic.util.PageList;
import cn.xy.org.domain.Department;
import cn.xy.org.query.DepartmentQuery;
import cn.xy.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 控制层
 */
@RestController
@RequestMapping("/dept")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    /**
     * 按id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")

    public Department queryById(@PathVariable("id") Long id){
        return departmentService.findById(5L);

    }

    /**
     * 查所有
     * @return
     */
    @GetMapping
    public List<Department> queryAll(){
        return departmentService.findAll();

    }

    /**
     * 高级查询和分页
     */
    @PostMapping
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query){
        return departmentService.queryPage(query);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @PreAuthorize(name="删除一条部门数据", value = "dept:deleteById")
    public AjaxResult romove(@PathVariable Long id){
        try {
            departmentService.remove(id);
            //成功返回AjaxResult的默认成功值
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙");
        }

    }

    /**
     * 新增和修改
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if(department.getId()==null){
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
            //无论新增或者修改成功都会返回成功值
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            //失败则返回失败信息
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }

    }

    /**
     * 批量删除
     */
    @PatchMapping
    public AjaxResult batchRemove(@RequestBody List<Long> ids){
        try {
            departmentService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败。");
        }

    }

    /**
     * 无限极树
     */
    @GetMapping("/tree")
    public List<Department> queryTree(){
        return departmentService.queryTree();

    }


}
